﻿using System;
using System.Collections.Generic;
using System.Text;
using WyUnity.Data.DataAccess;

namespace WyUnity.Data.Query
{
	[Serializable]
	class WhereGroup : WhereClip, IClip
	{
		private List<WhereClip> _list = new List<WhereClip>();
		private WhereConnect _connect;

		public WhereGroup(WhereClip el, WhereConnect connect)
		{
			_connect = connect;
			_list.Add(el);
		}
		public void Add(WhereClip clip, WhereConnect connect)
		{
			if (_connect != connect) throw new Exception("错误的条件,在一个组内不能同时出现and和or");
			_list.Add(clip);
		}

		public override WhereClip And(WhereClip andClip)
		{
			if (_connect != WhereConnect.And) throw new Exception("错误的条件,在一个组内不能同时出现and和or");
			_list.Add(andClip);
			return this;
		}

		public override WhereClip Or(WhereClip orClip)
		{
			if (_connect != WhereConnect.Or) throw new Exception("错误的条件,在一个组内不能同时出现and和or");
			_list.Add(orClip);
			return this;
		}

		public override string ToClip(ParameterProvider pp)
		{
			_parameters = pp;

			var sb = new StringBuilder();
			sb.Append("(");
			var first = true;
			_list.ForEach(el =>
						  {
							  if (first)
								  first = false;
							  else
								  sb.AppendFormat(" {0} ", _connect == WhereConnect.And ? "and" : "or");

							  sb.Append(((IClip)el).ToClip(pp));
						  });
			sb.Append(")");

			return sb.ToString();
		}
		[NonSerialized]
		private ParameterProvider _parameters;
		public override ParameterProvider Parameters
		{
			get
			{
				return _parameters;
			}
			protected set { }
		}
		public override string ToSqlClip(ISqlDialect dialect)
		{
			_parameters = new ParameterProvider(dialect, "W");
			return "where " + ToClip(_parameters);
		}

		public override List<string> GetAllField()
		{
			var list = new List<string>();
			_list.ForEach(el => list.AddRange(el.GetAllField()));
			return list;
		}
	}
}